#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 29 17:18:06 2025

@author: ulyanov
"""

import pygame
import random
from config import *

class Food:
    def __init__(self):
        self.position = (0, 0)
        self.spawn([])  # 初始生成位置
    
    def spawn(self, avoid_positions):
        """在需要避开的位置以外生成食物"""
        # 确保网格参数正确
        if GRID_WIDTH <= 0 or GRID_HEIGHT <= 0 or GRID_SIZE <= 0:
            print(f"警告: 无效的网格参数 - 宽: {GRID_WIDTH}, 高: {GRID_HEIGHT}, 大小: {GRID_SIZE}")
            return
            
        max_attempts = 100
        attempts = 0
        
        while attempts < max_attempts:
            x = random.randint(0, GRID_WIDTH - 1) * GRID_SIZE
            y = random.randint(0, GRID_HEIGHT - 1) * GRID_SIZE
            self.position = (x, y)
            
            # 确保食物不会生成在需要避开的位置上
            if self.position not in avoid_positions:
                break
                
            attempts += 1
        
        if attempts >= max_attempts:
            print("警告: 尝试多次后仍无法找到合适位置生成食物")
    
    def is_eaten(self, snake_head):
        """检查食物是否被蛇头吃到"""
        return self.position == snake_head
    
    def draw(self, surface):
        """绘制普通食物（红色）"""
        pygame.draw.rect(surface, RED, 
                        (self.position[0], self.position[1], 
                         GRID_SIZE, GRID_SIZE))


class SpecialFood(Food):
    def __init__(self):
        super().__init__()
        self.spawn_time = pygame.time.get_ticks()  # 记录生成时间
        self.duration = 5000  # 存在时间5000毫秒
        
    def draw(self, surface):
        """绘制特殊食物（黄色）"""
        # 添加闪烁效果，提醒玩家食物即将消失
        current_time = pygame.time.get_ticks()
        remaining = self.duration - (current_time - self.spawn_time)
        
        # 确保特殊食物可见性
        if remaining <= 0:
            return
            
        # 最后2秒开始闪烁
        if remaining < 2000:
            # 每300毫秒闪烁一次
            if int(current_time / 300) % 2 == 0:
                # 绘制半透明版本，而不是完全不绘制
                s = pygame.Surface((GRID_SIZE, GRID_SIZE), pygame.SRCALPHA)
                s.fill((*YELLOW, 100))  # 半透明黄色
                surface.blit(s, self.position)
                return
        
        # 正常绘制
        pygame.draw.rect(surface, YELLOW, 
                        (self.position[0], self.position[1], 
                         GRID_SIZE, GRID_SIZE))
    
    def is_expired(self):
        """检查特殊食物是否过期"""
        current_time = pygame.time.get_ticks()
        return current_time - self.spawn_time > self.duration